package com.wswy.wzcx.widget.home

import android.content.Context
import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.SPUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.home.ExtModule
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.ui.main.MainActivity
import com.wswy.wzcx.utils.ShareHelper
import com.wswy.wzcx.widget.OnItemClickListener

/**
 * 点击事件的id
 */
class ModuleItemClickListener(private val id:String) : OnItemClickListener<ExtModule> {

    override fun onItemClick(view: View?, t: ExtModule?) {
        t?.run {
            if (view != null && !handleItemClick(view.context,this)){
                //推啊广告特殊处理
                if (isTuiaAD) {
                    val ad = view.findViewById<View>(R.id.id_tuia_ad)
                    if (ad is View.OnClickListener) {
                        (ad as View.OnClickListener).onClick(ad)
                    }
                }
            }
        }
    }

    private fun handleItemClick(context: Context,itemData: ExtModule): Boolean {
        val intent: Intent? = RouterUtils.getIntent(context,itemData.targetType,itemData.targetUrl)
        var handle = false

        //分享app 特殊处理
        if (itemData.isNative && RPaths.share_app == itemData.targetUrl){
            ShareHelper.shareApp(context)
            handle = true
        }

        //跳转应用市场
        if (itemData.isNative && RPaths.gotoMarket == itemData.targetUrl){
            ShareHelper.gotoMarket(context)
            handle = true
        }

        if (itemData.isNative && RPaths.tuia_ad == itemData.targetUrl && context is MainActivity){
            handle = context.tuiaAd?.let {
                it.show()
                true
            }?:false
        }

        //原生页面或者web
        if (intent != null && !handle) {
            handle = kotlin.runCatching {
                context.startActivity(intent)
            }.isSuccess
        }

        //小程序启动
        if (itemData.isMiniProgram) {
            RouterUtils.startWxMiniProgram(itemData.targetUrl)

            handle = true
        }

        //点击统计，能显示的肯定是支持打开的，所以不准判断
        StatTools.sendShow(context, id, itemData.title)

        //记录点击次数
        if (!SPUtils.getInstance().getBoolean(itemData.spKey, false)) {
            SPUtils.getInstance().put(itemData.spKey, true)
        }

        return handle
    }
}